/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package BeanView;

import BeanSession.MbSLogin;
import Clases.Encrypt;
import Dao.DaoEmployee;
import HibernateUtil.HibernateUtil;
import Pojo.Employees;
import Pojo.Organization;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.context.RequestContext;

/**
 *
 * @author knyazev_o
 */
@ManagedBean
@ViewScoped
public class MbVEmployee implements java.io.Serializable{
    /**
     * Creates a new instance of MbVUsuario
     */
    private Session session;
    private Transaction transaction;
    private Employees employees;
    private List<Employees> listEmployee;
    private List<Employees> listEmployeeFiltered;
    private Organization organization;
    private List<Organization> selectedOrganization;
    //private String txtContraseniaRepita;
    //private UploadedFile avatar;    
    @ManagedProperty("#{mbSLogin}")
    private MbSLogin mbSLogin;
    
    public MbVEmployee() 
    {
        this.employees=new Employees();
        this.employees.setId(0L);
    }
    
    public void registration()
    {
        this.session=null;
        this.transaction=null;
        
        try
        {            
            DaoEmployee daoEmployee=new DaoEmployee();
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=session.beginTransaction();

            if(daoEmployee.getByLogin(this.session, this.employees.getLogin())!=null)
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка:", "Пользователь уже зарегистрирован в системе"));
                return;
            }
            this.employees.setNameFio(this.employees.getLastname().getName()+" "+
                                      this.employees.getFirstname().getName()+" "+
                                      this.employees.getMiddlename().getName());
            this.employees.setSnils(this.employees.getSnils().replaceAll("\\D", ""));
            this.employees.setPassword(Encrypt.sha512(this.employees.getPassword()));
            daoEmployee.register(this.session, this.employees);            
            this.transaction.commit();            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Успех:", "Регистрация прошла успешно"));
            this.employees=new Employees();
            this.employees.setId(0L);
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }
    
    public List<Employees> getAll()
    {
        this.session=null;
        this.transaction=null;
        
        try
        {
            DaoEmployee daoEmployee=new DaoEmployee();            
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=this.session.beginTransaction();            
            this.listEmployee=daoEmployee.getAll(this.session);            
            this.transaction.commit();            
            return this.listEmployee;
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));            
            return null;
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }

    public Employees getByLogin()
    {
        this.session=null;
        this.transaction=null;
        
        try
        {
            DaoEmployee daoEmployee=new DaoEmployee();            
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=this.session.beginTransaction();            
            HttpSession sessionEmployee=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);            
            this.employees=daoEmployee.getByLogin(this.session, sessionEmployee.getAttribute("login").toString());            
            this.transaction.commit();            
            return this.employees;
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));            
            return null;
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }
    
    public void update()
    {
        this.session=null;
        this.transaction=null;
        
        try
        {
            DaoEmployee daoEmployee=new DaoEmployee();            
            this.session=HibernateUtil.getSessionFactory().openSession();
            this.transaction=session.beginTransaction();
            if(daoEmployee.getByLoginDiferent(this.session, this.employees.getId(), this.employees.getLogin())!=null)
            {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка:", "Такой пользователь уже существует"));

                return;
            }
            daoEmployee.update(this.session, this.employees);            
            this.transaction.commit();            
            this.mbSLogin.setLogin(this.employees.getLogin());            
            HttpSession httpSession=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
            httpSession.setAttribute("login", this.employees.getLogin());            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Успех:", "Изменения были сохранены"));
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    }
    
    public void editorEmployee(Long id)
    {
        this.session=null;
        this.transaction=null;        
        try
        {
            DaoEmployee daoEmployee = new DaoEmployee();            
            this.session = HibernateUtil.getSessionFactory().openSession();
            this.transaction = session.beginTransaction();            
            this.employees = daoEmployee.getByIdEmployee(this.session, id);            
            RequestContext.getCurrentInstance().update("frmEditarUsuario:panelEditarUsuario");
            RequestContext.getCurrentInstance().execute("PF('dialogoEditarUsuario').show()");            
            this.transaction.commit();
        }
        catch(Exception ex)
        {
            if(this.transaction!=null)
            {
                this.transaction.rollback();
            }
            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Фатальная ошибка:", "Пожалуйста, обратитесь к администратору "+ex.getMessage()));
        }
        finally
        {
            if(this.session!=null)
            {
                this.session.close();
            }
        }
    } 
    
    public void setAddressEmployees(){
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parent",this.employees);
        RequestContext.getCurrentInstance().execute("PF('dialogAddress').show()");
    }    
    
    public void setOrganizationEmployees(){
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parent",this.employees);
        RequestContext.getCurrentInstance().execute("PF('dialogNewOrganization').show()"); 
    }
    
    public void setLastNameEmployees(){
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parent",this.employees);
        RequestContext.getCurrentInstance().execute("PF('dialogNewLastName').show()"); 
    }
    
    public void setFirstNameEmployees(){        
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parent",this.employees);
        RequestContext.getCurrentInstance().execute("PF('dialogNewFirstName').show()");        
    }
    
    public void setMiddleNameEmployees(){        
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parent",this.employees);
        RequestContext.getCurrentInstance().execute("PF('dialogNewMiddleName').show()");        
    }
    
    public Employees getEmployees() {
        return employees;
    }

    public void setEmployees(Employees employees) {
        this.employees = employees;
    }

    public List<Employees> getListEmployee() {
        return listEmployee;
    }

    public void setListEmployee(List<Employees> listEmployee) {
        this.listEmployee = listEmployee;
    }
    
    public List<Employees> getListEmployeeFiltered() {
        return listEmployeeFiltered;
    }

    public void setListEmployeeFiltered(List<Employees> listEmployeeFiltered) {
        this.listEmployeeFiltered = listEmployeeFiltered;
    }

    public MbSLogin getMbSLogin() {
        return mbSLogin;
    }

    public void setMbSLogin(MbSLogin mbSLogin) {
        this.mbSLogin = mbSLogin;
    }

    public Organization getOrganization() {
        return organization;
    }

    public List<Organization> getSelectedOrganization() {
        return selectedOrganization;
    }


    
    
    
}
